<?php

namespace app\home\controller;

use think\Controller;
use think\Request;

class Order extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        # 判断他是否登录，如果没有登录，就让他跳转到登录页面
        if(!session("?user_info")){
            # 将他当前请求的路径保存到session中，用于他登录后的路径跳转
            session("url_data","home/cart/index");
            # 跳转到登录页面
            return view("login/login");
        }
        # 查询到地址数据
        $user_id = session("user_info.id");
        # 查询地址
        $address = \app\common\model\Address::where("user_id",$user_id)->select();
        # 查询商品
        $goods = \app\home\logic\OrderLogic::addGoodsOrder();
        // dump($goods);die;
        $goods += [
            "address" => $address
        ];
        return view("order/index",["goods" => $goods]);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $params = input();
        // dump($params);die;
        $validate = $this->validate($params,[
            "address_id" => "require"
        ]);
        if($validate !== true){
            $this->error($validate);
        }
        $user_id = session("user_info.id");
        $address = \app\common\model\Address::where("id",$params["address_id"])->where("user_id",$user_id)->find();
        # 判断是否能查询到数据，如果查询不到那就是ID参数错误
        if(!$address){
            $this->error("数据异常");
        }
        # 因为里面的操作都是同时操作的一个失败那就全部都失败，所以使用事务
        # 开启事务
        \think\Db::startTrans();
        try{
            # 查询到购物车里面的数据 
            $goods = \app\home\logic\OrderLogic::addGoodsOrder();
            # 再进行添加订单的时候先进行一个仓库的检测
            # 判断仓库是否小于1 如果不仓库中数量充足就向下执行
            foreach ($goods["data"] as $key => $value) {
                if($value["number"] > $value["goods"]["goods_number"]){
                    # 如果数量过少那就进行异常的抛出
                    throw new \Exception("订单中包含的仓库不足");
                }
            }
            # 生成一个随机数 如一个时间戳
            $order_sn = time() . mt_rand(100000,999999);
            # 拼接一个订单数据
            $data = [
                "order_sn" => $order_sn, # 订单编号
                "user_id"  => $user_id, # 用户id
                "consignee" => $address["consignee"], # 用户姓名
                "address"   => $address["area"] . $address["address"], # 收货地址
                "phone"     => $address["phone"],   # 用户电话
                "goods_price" => $goods["totle_price"], # 商品总价格
                "shipping_price" => 0, # 邮费
                "coupon_price" => 0, # 优惠券折扣价
                "order_amount" => $goods["totle_price"] , # 应付款金额  总价 + 邮费 - 优惠券价格 = 一个真实价格
                "total_amount"  => $goods["totle_price"]
            ];
            # 添加订单数据
            // dump($goods["data"]);die;
            $res = \app\common\model\Order::create($data,true);
            $order_goods_data = [];
            foreach ($goods["data"] as $key => $value) {
                $order_goods_data[] = [
                    "order_id" => $res["id"],
                    "goods_id"  => $value["goods_id"],
                    "spec_goods_id" => $value["spec_goods_id"],
                    "number"   => $value["number"],
                    "goods_name" => $value["goods"]["goods_name"],
                    "goods_logo"    => $value["goods"]["goods_logo"],
                    "goods_price" => $value["goods"]["goods_price"],
                    "spec_value_names" => $value["spec_goods"]["value_names"],
                ];
            }
            $order_goods_model = new \app\common\model\OrderGoods();
            $order_goods_model->saveAll($order_goods_data);
            # 添加成功后，进行一个商品的增减 和 冻结
            $goods_data = [];
            $spec_goods = [];
            foreach($goods["data"] as $key => $value) {
                if($value["spec_goods_id"]){
                    # 冻结商品规格表的商品数量
                    $spec_goods[] = [
                        "id" => $value["spec_goods_id"],
                        "store_count" => $value["goods"]["goods_number"] - $value["number"],
                        "store_frozen" => $value["goods"]["frozen_number"] + $value["number"]
                    ];
                }else{
                    # 冻结商品表的商品数量
                    $goods_data[] = [
                        "id" => $value["goods_id"],
                        "goods_number" => $value["goods"]["goods_number"] - $value["number"],
                        "frozen_number" => $value["goods"]["frozen_number"] + $value["number"]
                    ];
                }
            }
            # 对goods表进行一个批量添加
            $goods_model = new \app\common\model\Goods();
            $goods_model->saveAll($goods_data);
            # 对SKU 商品规格表进行一个批量添加
            $spec_goods_model = new \app\common\model\SpecGoods();
            $spec_goods_model->saveAll($spec_goods);
            # 提交事物
            \think\Db::commit();
        }catch(\Exception $e){
            # 回滚事务
            \think\Db::rollback();
            $msg = $e->getMessage();
            $file = $e->getFile();
            $line = $e->getLine();
            trace("order,添加订单:" . $msg . $msg . $file . $line."error");
            $this->error($msg);
        }
        return $this->redirect("order/pay",["id" => $res["id"]]);

    }

    /**
     * 显示订单的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function pay($id)
    {
        # 定义支付的方式
        $pay = config("pyg_pay");
        # 获取到订单信息进行展示
        $order = \app\common\model\Order::where("id",$id)->find();
        return view("order/pay",["pay" => $pay,"order" => $order]);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
